#
#  Copyright (C) 2009 GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Antonio Santos Cadenas <jcaden __at__ gsyc __dot__ es>
#

import hashlib
import random

from social.privacy.config import privacy 
from config import DEFAULT_NODE_ICON

def rand_name():
    m = hashlib.md5()
    m.update(str(random.random()))
    return m.hexdigest()

def get_person(user):
    """
    Returns a Person object for User object "user" or None if not exists
    """
    from models import Person
    try:
        return Person.objects.get(id=user.id)
    except:
        return None

def add_node_to_group(node, group, data=[]):
    """
    Receives the models Social_node and Group and create a new Member
    """
    from models import Membership
    if Membership.objects.get_relation(node1=node, node2=group) == None:
        member=Membership(node1=node, node2=group)
        member.save()
        return True
    else:
        return False

def add_person_to_group(person, group, data=[]):
    """
    Receives the models Person and Group and create a new Member
    """
    return add_node_to_group(person, group, data)

def check_person_dict(person):
    #Check needed fields
    if "username" not in person:
        return None, "username field needed"
    if "password" not in person:
        return None, "password field needed"
    #Return ok
    return person, "Ok"

def check_note_dict(note):
    #Check needed fields
    if "title" not in note:
        return None, "title field needed"
    if "text" not in note:
        return None, "text field needed"
    if "latitude" not in note:
        return None, "latitude field needed"
    if "longitude" not in note:
        return None, "longitude field needed"
    if "owner" not in note:
        return None, "owner field needed"
    #Check optional fields
    if "altitude" not in note:
        note["altitude"]="0"
    #Return ok
    return note, "Ok"
    
def check_group_dict(group):
    #Check needed fields
    if "groupname" not in group:
        return None, "groupname field needed"
    #Check optional fields
    if "latitude" not in group:
        group["latitude"]="0"
    if "longitude" not in group:
        group["longitude"]="0"
    if "radius" not in group:
        group["radius"]="0"
    if "altitude" not in group:
        group["altitude"]="0"
    #Return ok
    return group, "Ok"

def check_photo_dict(photo):
    #Check needed fields
    if "photo_name" not in photo:
        return None, "photo_name field needed"
    if "photo_data" not in photo:
        return None, "photo_data field needed"
    if "description" not in photo:
        return None, "description field needed"
    if "latitude" not in photo:
        return None, "latitude field needed"
    if "longitude" not in photo:
        return None, "longitude field needed"
    if "uploader" not in photo:
        return None, "uploader field needed"
    #Check optional fields
    if "radius" not in photo:
        photo["radius"]=""
    if "altitude" not in photo:
        photo["altitude"]="0"
    #Return ok
    return photo, "Ok"

def check_sound_dict(photo):
    #Check needed fields
    if "sound_name" not in photo:
        return None, "sound_name field needed"
    if "sound_data" not in photo:
        return None, "sound_data field needed"
    if "description" not in photo:
        return None, "description field needed"
    if "latitude" not in photo:
        return None, "latitude field needed"
    if "longitude" not in photo:
        return None, "longitude field needed"
    if "uploader" not in photo:
        return None, "uploader field needed"
    #Check optional fields
    if "radius" not in photo:
        photo["radius"]=""
    if "altitude" not in photo:
        photo["altitude"]="0"
    #Return ok
    return photo, "Ok"

def get_correct_size(max_w, max_h, w, h):
    """
        Returns the correct width and heigth with the same proportion as
        w,h tuple and not exceeding the maximum w and h indicated
    """
    new_ratio = float(max_h)/float(max_w)
    ratio = float(h)/float(w)
    if ratio>new_ratio:
        return int(max_h/ratio), max_h
    else:
        return max_w, int(max_w*ratio)

def get_fields_for_groups(obj, groups):
    """
    Returns  all the fields for the groups in the list using the privacy 
    configuration file
    
    @param groups: A list of groups
    @param obj: The object requested 
    
    @return: The fields in the groups  
    """
    try:
        p_obj=privacy[obj.__module__][obj.__class__.__name__]
    except:
        return []
    fields=[]
    for g in groups:
        try:
            fields+=p_obj[g]
        except:
            pass
    return fields

def get_group_for_field(obj, field):
    """
    Returns the group where the field is in
    
    @param obj: The requested object
    @param field: The field  
    
    @return: The group for the field
    """
    try:
        p_obj=privacy[obj.__module__][obj.__class__.__name__]
    except:
        return None
    for g in p_obj.keys():
        if field in p_obj[g]:
            return g;
    return None

def set_default_icon(obj):
    
    obj.icon = DEFAULT_NODE_ICON
        
    